package com.baitengsoft.patentapimonitor.api.service.impl;

import com.baitengsoft.patentapimonitor.api.dao.SysAdminUserTokenDao;
import com.baitengsoft.patentapimonitor.api.entity.SysAdminUserTokenEntity;
import com.baitengsoft.patentapimonitor.api.oauth2.TokenGenerator;
import com.baitengsoft.patentapimonitor.api.service.SysAdminUserTokenService;
import com.baitengsoft.patentapimonitor.common.utils.Res;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service("sysAdminUserTokenService")
public class SysAdminUserTokenServiceImpl implements SysAdminUserTokenService {
	@Autowired
	private SysAdminUserTokenDao sysAdminUserTokenDao;
	//12小时后过期
	private final static int EXPIRE = 3600 * 12;

	@Override
	public SysAdminUserTokenEntity queryByUserId(Long userId) {
		return sysAdminUserTokenDao.queryByUserId(userId);
	}

	@Override
	public void save(SysAdminUserTokenEntity token){
		sysAdminUserTokenDao.save(token);
	}
	
	@Override
	public void update(SysAdminUserTokenEntity token){
		sysAdminUserTokenDao.update(token);
	}

	@Override
	@Transactional
	public Res createToken(long userId) {
		//生成一个token
		String token = TokenGenerator.AdmingenerateValue();

		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//判断是否生成过token
		SysAdminUserTokenEntity tokenEntity = queryByUserId(userId);
		if(tokenEntity == null){
			tokenEntity = new SysAdminUserTokenEntity();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//保存token
			save(tokenEntity);
		}else{
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//更新token
			update(tokenEntity);
		}

		Res r = Res.ok().put("token", token).put("expire", EXPIRE);

		return r;
	}

	@Override
	public void logout(long userId) {
		//生成一个token
		String token = TokenGenerator.AdmingenerateValue();

		//修改token
		SysAdminUserTokenEntity tokenEntity = new SysAdminUserTokenEntity();
		tokenEntity.setUserId(userId);
		tokenEntity.setToken(token);
		update(tokenEntity);
	}
}
